package to3;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class ArtikelBestellenFrame extends javax.swing.JFrame {

    private OnderdelenLijst o1;
    private List<Onderdeel> oList;
    private BestellingLijst b1;
    private BestellingLijst b2;
    private List<Bestelling> bList;
    
    public ArtikelBestellenFrame() {
        initComponents();
        setVisible(true);
        
                ////////SCHERM IN MIDDEN////////
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension windowSize = this.getSize();

        int windowX = Math.max(0, (screenSize.width  - windowSize.width ) / 2);
        int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);

        this.setLocation(windowX, windowY);
        ///////////////////////////////
        
        o1 = new OnderdelenLijst();
        b1 = new BestellingLijst();
        b2 = new BestellingLijst();
        oList = new ArrayList<>();
       // bList = new ArrayList<>();
            
          try {
            readFile2();
        } catch (IOException ex) {
            Logger.getLogger(ParkerenFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
          fillOnderdelenList();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        aantalOnderdelen = new javax.swing.JTextField();
        artikelNaam = new javax.swing.JComboBox();
        btn_bestelOnderdelen = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        btn_ArtikelenToevoegen = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Voorraad Beheren");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Artikelnaam:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Aantal:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Artikelen bestellen");

        jButton4.setText("Hoofdmenu");
        jButton4.setPreferredSize(new java.awt.Dimension(164, 46));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        aantalOnderdelen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aantalOnderdelenActionPerformed(evt);
            }
        });

        btn_bestelOnderdelen.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        btn_bestelOnderdelen.setText("Bestellen");
        btn_bestelOnderdelen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_bestelOnderdelenActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(1);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        btn_ArtikelenToevoegen.setText("voeg toe");
        btn_ArtikelenToevoegen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ArtikelenToevoegenActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(341, 341, 341)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(btn_bestelOnderdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(54, 54, 54)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jLabel5)
                                                .addGroup(layout.createSequentialGroup()
                                                    .addComponent(jLabel3)
                                                    .addGap(18, 18, 18)
                                                    .addComponent(artikelNaam, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(layout.createSequentialGroup()
                                                    .addComponent(jLabel4)
                                                    .addGap(47, 47, 47)
                                                    .addComponent(aantalOnderdelen, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                        .addGroup(layout.createSequentialGroup()
                                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(btn_ArtikelenToevoegen)))
                        .addGap(0, 447, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(artikelNaam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(aantalOnderdelen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_ArtikelenToevoegen))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btn_bestelOnderdelen)
                .addGap(77, 77, 77)
                .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void fillOnderdelenList(){
        List<Onderdeel> tempList = o1.getOnderdelen();
            String s = "";
            for (Onderdeel o: tempList){
                if (o.getAantalVoorraad() > 0){
                s = s + o.getOmschrijving() + ",";
                }
            }
            final String[] sarray = stringtoArray( s, ",");
            artikelNaam.setModel(new javax.swing.DefaultComboBoxModel() {
            String[] strings = sarray;
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
    }
    
     private String[] stringtoArray( String s, String sep ) {
  // convert a String s to an Array, the elements
  // are delimited by sep
  // NOTE : for old JDK only (<1.4).
  //        for JDK 1.4 +, use String.split() instead
  StringBuffer buf = new StringBuffer(s);
  int arraysize = 1;
  for ( int i = 0; i < buf.length(); i++ ) {
    if ( sep.indexOf(buf.charAt(i) ) != -1 )
      arraysize++;
  }
  String [] elements  = new String [arraysize];
  int y,z = 0;
  if ( buf.toString().indexOf(sep) != -1 ) {
    while (  buf.length() > 0 ) {
      if ( buf.toString().indexOf(sep) != -1 ) {
        y =  buf.toString().indexOf(sep);
        if ( y != buf.toString().lastIndexOf(sep) ) {
          elements[z] = buf.toString().substring(0, y ); 
          z++;
          buf.delete(0, y + 1);
        }
        else if ( buf.toString().lastIndexOf(sep) == y ) {
          elements[z] = buf.toString().substring
            (0, buf.toString().indexOf(sep));
          z++;
          buf.delete(0, buf.toString().indexOf(sep) + 1);
          elements[z] = buf.toString();z++;
          buf.delete(0, buf.length() );
        }
      }
    }
  }
  else {
    elements[0] = buf.toString(); 
  }
  buf = null;
  return elements;
}
     
     
       private void readFile3() throws IOException {
                    b1.clearBestellingLijst();
                    FileReader fr = new FileReader("ProductBestellingen.txt");
                    BufferedReader br = new BufferedReader(fr);

                    while (true) {
                        String regel = br.readLine();
                        if (regel == null) {
                        break;
                    }
                    Scanner sc = new Scanner(regel);
                    sc.useDelimiter("\\s*,\\s*");
                    String bestelNummer = sc.next();
                    String omschrijving = sc.next();
                    String aantal = sc.next();
                    int aantalInt = Integer.parseInt(aantal);
                    b1.addBestelling(bestelNummer, omschrijving, aantalInt);
                    sc.close();
                    }
        }
       
       private void readFile4() throws IOException {
                    b2.clearBestellingLijst();
                    FileReader fr = new FileReader("BrandstofBestellingen.txt");
                    BufferedReader br = new BufferedReader(fr);

                    while (true) {
                        String regel = br.readLine();
                        if (regel == null) {
                        break;
                    }
                    Scanner sc = new Scanner(regel);
                    sc.useDelimiter("\\s*,\\s*");
                    String bestelNummer = sc.next();
                    String omschrijving = sc.next();
                    String aantal = sc.next();
                    String tankId = sc.next();
                    int aantalInt = Integer.parseInt(aantal);
                    b2.addBestelling(bestelNummer, omschrijving, aantalInt, tankId);
                    sc.close();
                    }
        }
       
       private void writeBestelling() throws IOException{
                    List<Bestelling> listB = b1.getBestellingen();
                    FileWriter fw	 = new FileWriter("ProductBestellingen.txt");
                    PrintWriter pw	 = new PrintWriter(fw);
                    boolean eersteKeer = false;
                    for (Bestelling on : listB){
                    if(eersteKeer == false){
                        pw.print(on.getBestelNummer() + ", " + on.getOmschrijving() + ", " + on.getAantal() + "\n");
                    }
                    else{
                        pw.print("\n" + on.getBestelNummer() + ", " + on.getOmschrijving() + ", " + on.getAantal());
                 }
                }
                    
  		pw.close();
                fw.close();
    }
       
       private void writeBestelling2() throws IOException{
                    List<Bestelling> listB = b2.getBestellingen();
                    FileWriter fw	 = new FileWriter("BrandstofBestellingen.txt");
                    PrintWriter pw	 = new PrintWriter(fw);
                    boolean eersteKeer = false;
                    for (Bestelling on : listB){
                    if(eersteKeer == false){
                        pw.print(on.getBestelNummer() + ", " + on.getOmschrijving() + ", " + on.getAantal() + ", " + on.getTankId() + "\n");
                    }
                }
                    
  		pw.close();
                fw.close();
    }
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        hoofdMenu hM = new hoofdMenu();
        this.setVisible(false);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void aantalOnderdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aantalOnderdelenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_aantalOnderdelenActionPerformed

    private void btn_bestelOnderdelenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_bestelOnderdelenActionPerformed
         if(!oList.isEmpty()) {
             b1.clearBestellingLijst();
             try {
                readFile3();
            } catch (IOException ex) {
                Logger.getLogger(ArtikelBestellenFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            String bNummer = b1.generateBestelnr();
            for (Onderdeel oo : oList){
                b1.addBestelling(bNummer, oo.getOmschrijving(), oo.getAantal());
            }
            try {
                writeBestelling();
                JOptionPane.showMessageDialog(null, "Uw bestelling is geplaatst met bestelnummer: " + bNummer,  "BESTELD", JOptionPane.OK_OPTION);
            } catch (IOException ex) {
                Logger.getLogger(ArtikelBestellenFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }else {
                JOptionPane.showMessageDialog(null, "geen onderdelen gevonden",  "Fout", JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_btn_bestelOnderdelenActionPerformed

    private void btn_ArtikelenToevoegenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ArtikelenToevoegenActionPerformed
        if (aantalOnderdelen.getText().matches("[0-9]{1,3}")) {
            if (artikelNaam.getSelectedItem() != null) {
                Onderdeel tempO = o1.getOnderdeel(artikelNaam.getSelectedItem().toString());
               
                    tempO.setAantal(Integer.parseInt(aantalOnderdelen.getText()));
                    if (oList.contains(tempO)) {
                        oList.remove(tempO);
                    }
                    oList.add(tempO);
                    fillBestelOnderdelenList(oList);
            } else {
                JOptionPane.showMessageDialog(null, "Geen onderdeel gekozen", "Fout", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "incorrect aantal (1-9999)", "Fout", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btn_ArtikelenToevoegenActionPerformed

    private void fillBestelOnderdelenList(List<Onderdeel> oList){
        String s = "";
        for (Onderdeel d1 : oList){
            s = s + d1.getOmschrijving() + "       " + d1.getAantal() + "\n";  
        }
         jTextArea1.setText(s);
    }
    
    private void readFile2() throws IOException {
                o1.clearOnderdelenLijst();
		FileReader fr = new FileReader("onderdelen.txt");
                BufferedReader br = new BufferedReader(fr);

                    while (true) {
                    String regel = br.readLine();
                    if (regel == null) {
                    break;
                    }
                    Scanner sc = new Scanner(regel);
                    sc.useDelimiter("\\s*,\\s*");
                    String onderdeel = sc.next();
                    String prijsPerAantalString = sc.next();
                    double prijsPerAantal = Double.parseDouble(prijsPerAantalString);
                    String aantal = sc.next();
                    int aantalVoorraad = Integer.parseInt(aantal);
                    o1.addOnderdeel(onderdeel, prijsPerAantal, aantalVoorraad);
                    sc.close();
                    }
        }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField aantalOnderdelen;
    private javax.swing.JComboBox artikelNaam;
    private javax.swing.JButton btn_ArtikelenToevoegen;
    private javax.swing.JButton btn_bestelOnderdelen;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
